﻿using System.Net;
using System.Net.Http.Json;

namespace iOSClub.App.Share.Serves;

public class UserServer : IServer
{
    public UserServer()
    {
    }

    public UserServer(string jwt) : base(jwt)
    {
    }

    public UserServer(IServer server) : base(server)
    {
    }

    public async Task<string> Login(LoginModel model)
    {
        try
        {
            using var result = await httpClient.PostAsJsonAsync($"{_url}/Member/Login", model);
            if (result.StatusCode == HttpStatusCode.NotFound) return "登录失败";
            Jwt = await result.Content.ReadAsStringAsync();
            return Jwt;
        }
        catch
        {
            return "";
        }
    }

    public async Task<MemberModel?> GetData()
    {
        if (string.IsNullOrEmpty(Jwt)) return null;
        try
        {
            return await httpClient.GetFromJsonAsync<MemberModel>($"{_url}/Member/GetData");
        }
        catch
        {
            return null;
        }
    }

    public async Task<string> SignUp(StudentModel model)
    {
        try
        {
            var result = await httpClient.PostAsJsonAsync($"{_url}/Member/SignUp", model);
            if (!result.IsSuccessStatusCode) return "";
            Jwt = await result.Content.ReadAsStringAsync();
            return Jwt;
        }
        catch
        {
            return "";
        }
    }

    public async Task<bool> Update(MemberModel model)
    {
        try
        {
            var result = await httpClient.PutAsJsonAsync($"{_url}/Member/Update/{model.UserId}", model);
            return result.IsSuccessStatusCode;
        }
        catch
        {
            return false;
        }
    }

    public async Task<string[]> GetAcademies()
    {
        try
        {
            return await httpClient.GetFromJsonAsync<string[]>($"{_url}/Member/GetAcademies") ?? [];
        }
        catch
        {
            return [];
        }
    }
}